#!/bin/sh

function ask()
{
    echo -n "$@" '[Y/n] ' ; read ans
    case "$ans" in
        y*|Y*|'') return 0 ;;
        *) return 1 ;;
    esac
}

echo "This script will install clupower (cluster power manager)."

if [ "$UID" -ne "0" ]
then
  echo "You must be root to install clupower."
  exit 1
fi

echo -n "Enter destination directory or press enter to use the default [/opt/clupower] "; read DESTDIR

if [[ -z $DESTDIR ]]
then
  DESTDIR="/opt/clupower"
fi

if [ -e "$DESTDIR" ] && ask "Destination folder exists. Overwrite?"
then
  rm -rf $DESTDIR/lib
fi

echo -n "Enter executables directory or press enter to use the default [/usr/bin] "; read BINDIR

if [[ -z $BINDIR ]]
then
  BINDIR="/usr/bin"
fi

mkdir -p $DESTDIR
cp -r lib $DESTDIR
echo "\$cpversion = '$(cat version)'" > $DESTDIR/lib/version.rb
mv $DESTDIR/lib/clupower_settings.yml $DESTDIR
LIB=$DESTDIR/lib
sed "s|__LIB__|$LIB|" $DESTDIR/lib/cpman > $BINDIR/cpman
sed "s|__LIB__|$LIB|" $DESTDIR/lib/ipmi_start > $BINDIR/ipmi_start
sed --in-place "s|__DEST__|$DESTDIR|" $DESTDIR/clupower_settings.yml
rm $DESTDIR/lib/{cpman,ipmi_start}
chmod +x $BINDIR/{cpman,ipmi_start}
chown -R root:root $DESTDIR
chmod 0700 $DESTDIR
cat INSTALL_NOTES
